function InstallFunction(obj,functionName)
{
  obj[functionName] = function() { Request(functionName,arguments,'/rpc'); }
}

var server = {};
InstallFunction(server,'addEntity');
InstallFunction(server,'checkUser');
InstallFunction(server,'deleteEntity');
InstallFunction(server,'deleteUserRight');
InstallFunction(server,'getEntityListing');
InstallFunction(server,'getEntityEditForm');
InstallFunction(server,'getHelpTopic');
InstallFunction(server,'initSetup');
InstallFunction(server,'populateHelpTopics');
InstallFunction(server,'saveEntity');
InstallFunction(server,'saveAdmin');
InstallFunction(server,'saveHelp');

function AddEntity(entity_type) {
  server.addEntity(entity_type,AddEntitySuccess);
}

function AddEntitySuccess(response) {
  if(response) {
    $('#cataloger-action-display').html(response);
  } else {
    $('#cataloger-action-display').html("eCataloger unable to retrieve form");
  }
}

function AddUserRight(user_type,select_id)
{
  var select_element = document.getElementById(select_id);
  var user_email = prompt("Please enter valid Google account e-mail:");
  server.checkUser([user_email,select_id,user_type],AddUserRightSuccess);
}

function AddUserRightSuccess(response)
{
  if(response)
  {
    var select_element = document.getElementById(response['select_id']);

	var user_exists = false;
	for(var i=0;i<select_element.options.length;i++)
	{
	  if(select_element.options[i].text == response['user_email'])
	  {
	    user_exists = true;
	  }
	}
	if(!user_exists)
	{
	  select_element.add(new Option(response['user_email'],response['user_id']));
	}
  } else {
    alert("Did not add user");
  }
}

function AddHelp()
{
 $("#id-help_question").attr('disabled',false);
 $("#id-help_answer").attr('disabled',false);
 $("#id-save-help-topic-btn").attr('disabled',false);
 $("#id-add-help-topic-btn").attr('disabled',true);
 $("#id-help_question").attr('value','');
 $("#id-help_answer").attr('value','');
 $("#id-help-key").attr('value','');
}
function DeleteEntity(entity_key) {
 server.deleteEntity(entity_key,DeleteEntitySuccess);
}

function DeleteEntitySuccess(response) {
  if(response) {
   $('#cataloger-action-display').html(response);
  } else {
   $('#cataloger-action-display').html("eCataloger unable to delete entity");
  }
}

function DisplayEntity(entity_key) {
 alert("DISPLAY ENTITY w/ key=" + entity_key + " still needs implementing");
}

function EditAdmin()
{
  $("#id-save-admin-btn").attr('disabled',false);
  $("#id-app_name").attr('disabled',false);
  $("#id-set-up-corp-bodies").attr('disabled',false);
  $("#id-institution-select").attr('disabled',false);
  $("#id-mve-admin-btn").attr('disabled',false);
  $("#id-rmv-admin-btn").attr('disabled',false);
  $("#id-add-admin-btn").attr('disabled',false);
  $("#id-start_ip").attr('disabled',false);
  $("#id-end_ip").attr('disabled',false);
  $("#id-edit-admin-btn").attr('disabled',true);

}

function EditEntity(entity_key) {
 server.getEntityEditForm(entity_key,EditEntitySuccess);
}

function EditEntitySuccess(response) {
  if(response) {
    $("#cataloger-action-display").html(response);
  } else {
    $("#cataloger-action-display").html("eCataloger could not retrieve edit form");
  }
}

function EditHelpTopic()
{

  $("#id-help_question").attr('value','');
  $("#id-help_answer").attr('value','');
  $("#id-edit-help-topic-btn").attr('disabled',true);
  $("#id-save-help-topic-btn").attr('disabled',false);
  server.getHelpTopic($("#id-help-topics-select").attr('value'),EditHelpTopicSuccess);

}

function EditHelpTopicSuccess(response)
{
 if(response)
 {
  $("#id-help-key").attr('value',response['topic_key']);
  $("#id-help_question").attr('value',response['question']);
  $("#id-help_question").attr('disabled',false);
  $("#id-help_answer").attr('value',response['answer']);
  $("#id-help_answer").attr('disabled',false);
  $("#id-add-help-topic-btn").attr('disabled',true);
 } else {
   alert("Could not edit Help Topic");
 }
}

function GetEntity(entity_type,calling_element_id) {
  var hidden_element = document.getElementById('id_calling_element');
  hidden_element.value = calling_element_id;
  $('#id-dialog-entity-results').html('');
  $('#get-entity-dialog').dialog('option','title','Get ' + entity_type);
  $('#get-entity-dialog').dialog('open');
}

function GetEntityListing(entity_name) {
  server.getEntityListing(entity_name,GetEntityListingSuccess);
}

function GetEntityListingSuccess(response) {
  var dialog_results = document.getElementById('id-dialog-entity-results');
  var output_str = '<table>';
  if(response) {
	for(var i=0;i < response.length;i++) {
      output_str += '<tr><td><input type="checkbox" name="dialog_entity_key" id="id_entity_' + i + '" value="' + response[i]['key'] +'"></td>';
	  if(response[i]['display_label']) {
	    output_str += '<td>' + response[i]['display_label'] + '</td>';
	  } else if (response[i]['display_form']) {
	    output_str += '<td>' + response[i]['display_form'] + '</td>';
	  } else if(response[i]['value']) {
	    output_str += '<td>' + response[i]['value'] + '</td>';
	  } else {
	    output_str += '<td>' + response[i]['key'] + '</td>';
	  }
	  output_str += '</tr>';
	}
	output_str += '</table>';
	dialog_results.innerHTML = output_str;
  } else {
    dialog_results.innerHTML = "No entities found";
  }
}

function InitConfig()
{
  var output = new Array();
  output[0] = $("#id-initial-admin").attr('value');
  if($("#id-admin-chkbx").attr('checked')){ output[1] = true; } else { output[1]=false; }
  if($("#id-editor-chkbx").attr('checked')) {output[2] = true;} else { output[2] =false;}
  if($("#id-contributor-chkbx").attr('checked')) {output[3] = true;} else {output[3] = false;}
  output[4] = $("#id-init-app-name").attr('value');
  output[5] = $("#id-init-corp-name").attr('value');
  output[6] = $("#id-init-corp-addr").attr('value');
  server.initSetup(output,InitConfigSuccess);
}

function InitConfigSuccess(response)
{
  if(response)
  {
    window.location.reload();
  } else {
    alert("Unable to configure set-up");
  }
}

function PopulateDisplay(select_element_id) {
  var select_element = document.getElementById(select_element_id);
  var entity_name = select_element.options[select_element.selectedIndex].value;
  GetEntityListing(entity_name);
}

function PopulateHelpTopics()
{
  var topic_type = $("#id-help_type_of").attr('value');
  $("#id-help_question").attr('value','');
  $("#id-help_answer").attr('value','');
  $("#id-edit-help-topic-btn").attr('disabled',false);
  server.populateHelpTopics(topic_type,PopulateHelpTopicsSuccess);
}

function PopulateHelpTopicsSuccess(response)
{
  if (response)
  {
   $("#id-help-topics-select").html(response);
  } else {
    //alert("Could not load current Help Topics");
  }
}

function RemoveUserRight(user_type,select_id)
{
  var select_element = document.getElementById(select_id);
  var user_right_key = select_element.options[select_element.selectedIndex].value;
  switch(user_type)
  {
    case "Administrators":
	  server.deleteUserRight(user_right_key,RemoveAdminUserRight);
	  break;

	case "Editors":
	  server.deleteUserRight(user_right_key,RemoveEditorUserRight);
	  break;

	case "Contributors":
	  server.deleteUserRight(user_right_key,RemoveContributorUserRight);
	  break;

	default:
	  alert("Unknown user right type: " + user_type);
	  break;
  }

}

function RemoveAdminUserRight(response)
{
 if(response)
 {
   var deleted_key = response;
   $("#id-add-admin-user-btn").attr("disabled",false);
   $("#id-delete-admin-user-btn").attr("disabled",true);
   alert("SELECTED VALUE IS " + $("#id-admin-users option:selected").attr("value"));
  } else {
   alert("Unable to remove user from administrator role");
  }

}

function RemoveContributorUserRight(response)
{
 if(response)
 {
   var deleted_key = response;
   $("#id-add-contrib-user-btn").attr("disabled",false);
   $("#id-delete-contrib-user-btn").attr("disabled",true);
   alert("SELECTED VALUE IS " + $("#id-contrib-users option:selected").attr("value"));
  } else {
   alert("Unable to remove user from contributorcd  role");
  }
}

function RemoveEditorUserRight(response)
{

}

function SaveAdmin()
{
  var admin_array = new Array();
  if(!$("#id-institution-select").attr('value'))
  {
    alert("eCataloger must have an associated Institution");
  } else {
	  $("#id-save-admin-btn").attr('disabled',true);
	  $("#id-app_name").attr('disabled',true);
	  $("#id-set-up-corp-bodies").attr('disabled',true);
	  $("#id-institution-select").attr('disabled',true);
	  $("#id-mve-admin-btn").attr('disabled',true);
	  $("#id-rmv-admin-btn").attr('disabled',true);
	  $("#id-add-admin-btn").attr('disabled',true);
      $("#id-start_ip").attr('disabled',true);
      $("#id-end_ip").attr('disabled',true);
	  $("#id-edit-admin-btn").attr('disabled',false);
	  server.saveAdmin({'app_name':$("#id-app_name").attr('value'),
	                    'institution_key':$("#id-institution-select").attr('value'),
					    'start_ip':$("#id-start_ip").attr('value'),
					    'end_ip':$("#id-end_ip").attr('value')},SaveAdminSuccess);
  }
}

function SaveAdminSuccess(response)
{
  alert(response);
}

function SaveEntity(submit_input) {
 var form_data = submit_input.form;
 var form_info = [];
 for(var i=0;i < form_data.elements.length;i++) {
    var input_element = form_data.elements[i];
	var record = [];
	switch(input_element.type) {
	  case 'radio':
	  case 'checkbox':
	    if(input_element.checked) {
		  record.push(input_element.name);
	      record.push(input_element.value);
		  form_info[i]=record;
		}
		break;
	  default:
	    if(input_element.value.length > 0) {
		 record.push(input_element.name);
	     record.push(input_element.value);
		 form_info[i] = record;
		}
	}

  }
 server.saveEntity(form_info,SaveEntitySuccess);
 return false;
}

function SaveEntitySuccess(response) {
  if(response) {
	$("#cataloger-action-display").html("Entity saved to datastore, key is " + response + " <a href=\"#\" onclick=\"DeleteEntity('" + response +"');\">Undo</a>");

  } else {
    $("#cataloger-action-display").html("Error trying to save to datastore");
  }
}

function SaveHelp()
{
 $("#id-help_question").attr('disabled',true);
 $("#id-help_answer").attr('disabled',true);
 $("#id-save-help-topic-btn").attr('disabled',true);
 $("#id-add-help-topic-btn").attr('disabled',false);
 var save_array = {'question':$("#id-help_question").attr('value'),'answer':$("#id-help_answer").attr('value')};
 if ($("#id-help-key").attr('value'))
 {
   save_array['help_key'] = $("#id-help-key").attr('value');
 }
 var type_of = $("#id-help_type_of").attr('value');
 if(type_of == 'all')
 {
   save_array['type_of'] = 'general';
 } else {
   save_array['type_of'] = type_of;
 }
 server.saveHelp(save_array,SaveHelpSuccess);
}

function SaveHelpSuccess(response)
{
  if(response)
  {
    $("#id-help_key").attr('value',response['help_key']);
	$("#id-help_question").attr('value','');
	$("#id-help_answer").attr('value','');
	alert(response['message']);
  } else {
    alert("Failed to save help");
  }
}

function UpdateCallingElement() {
  var saved_element = document.getElementById('id_calling_element');
  var calling_div = document.getElementById(saved_element.value);
  var entities_values = document.getElementsByName('dialog_entity_key');
  var output_str = '';
  for(var i=0;i < entities_values.length;i++) {
    var input_chkbox = entities_values[i];
	if(input_chkbox.checked) {
	  var new_ckbox = document.createElement('input');
	  new_ckbox.type = 'checkbox';
	  new_ckbox.checked = true;
	  new_ckbox.value = input_chkbox.value;
	  new_ckbox.name = saved_element.value.substring(3,saved_element.value.length-4);
	  calling_div.appendChild(new_ckbox);
	  var new_span = document.createElement('span');
	  new_span.innerHTML = input_chkbox.value + '<br/>';
	  calling_div.appendChild(new_span);
	}
  }
}

function UserRightSelectHandler(add_btn_id,rmv_btn_id)
{
  var add_btn = document.getElementById(add_btn_id);
  var rmv_btn = document.getElementById(rmv_btn_id);
  add_btn.disabled = false;
  rmv_btn.disabled = false;
}

